package minidb.index;

import static minidb.type.Const.*;
import minidb.buffer.*;
import minidb.record.TableInfo;

public class bTreeRoot {
	private String fieldName;
	private int next;
	private TYPE type;
	private int pageNum;
	private int length;
	private int isOnly;
	public bTreeRoot(Buffer buf, TableInfo table){
		this.length = 0;
		this.pageNum = buf.pageNum();
		int pos = INT_SIZE * 4;
		this.next = buf.getInt(pos);
		length+=INT_SIZE;
		this.fieldName = buf.getString(pos+length);
		length+=fieldName.length()+1;
		this.isOnly = buf.getInt(pos+length);
		length+=INT_SIZE;
		this.type = table.getField(fieldName).type();
	}
	
	public bTreeRoot(Buffer buf){
		int pos = INT_SIZE * 4;
		this.next = buf.getInt(pos);
	}
	public int next(){	return this.next;	}
	
	public void next(int next){
		this.next = next;
	}
	
	public TYPE type(){	return this.type; }
	
	public int length(){ return this.length; }
	
	public int pageNum(){ return this.pageNum; }
	
	public String fieldName(){ return this.fieldName; }
	
	public boolean isOnly(){
		return this.isOnly > 0;
	}
	
	public byte[] array(){
		java.nio.ByteBuffer buf = java.nio.ByteBuffer.allocateDirect(length);
		buf.rewind();
		buf.putInt(this.next);
		buf.put((byte)fieldName.length());
		buf.put(fieldName.getBytes());
		buf.putInt(this.isOnly);
		byte []bt = new byte[length];
		buf.rewind();
		buf.get(bt);
		return bt;
	}
	
}
